package com.neuedu.service.impl;

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.neuedu.service.MinioService;
import com.neuedu.service.VoiceService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.ByteBuffer;

@Service
public class VoiceServiceImpl implements VoiceService {
    @Value("${ai.yinpin.model}")
    String model;
    @Value("${ai.yinpin.voice}")
    String voice;
    @Value("${ai.api_key}")
    String api_key;
    @Resource
    MinioService minioService;
    @Override
    public String getVoice(String message, String sessionId) {
        SpeechSynthesisParam param =
                SpeechSynthesisParam.builder()
                        .model(model) // 模型
                        .voice(voice) // 音色
                        .volume(10)
                        .apiKey(api_key)
                        .build();
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
        ByteBuffer audio = null;
        try {
            // 阻塞直至音频返回
            audio = synthesizer.call(message);
            return minioService.mianshi(100L, audio.array(), "interview" + sessionId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 任务结束关闭websocket连接
            synthesizer.getDuplexApi().close(1000, "bye");
        }
    }
}
